<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['goods:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['goods:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板编号" width="180" align="center" prop="id" />
      <el-table-column label="模板名称" width="180" align="center" prop="name" />
      <el-table-column label="关联品牌" align="center" prop="brandIds">
        <template slot-scope="scope">
          {{transformStringArray(scope.row.brandIds)}}
        </template>
      </el-table-column>
      <el-table-column label="关联规格" align="center" prop="specIds" >
        <template slot-scope="scope">
          {{transformStringArray(scope.row.specIds)}}
        </template>
      </el-table-column>
      <el-table-column label="拓展属性" align="center" prop="attributeItems" >
        <template slot-scope="scope">
          {{transformStringArray(scope.row.attributeItems)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模板管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="关联品牌" prop="brandIds">
          <el-select v-model="brandIds" multiple placeholder="请选择品牌" style="width: 100%">
            <el-option
              v-for="item in brandArray"
              :key="item.id"
              :label="item.brandName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联规格" prop="specIds">
          <el-select v-model="specIds" multiple placeholder="请选择规格" style="width: 100%">
            <el-option
              v-for="item in specArray"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="拓展属性" prop="attributeItems">
          <el-button @click="tableData.push({})">新增拓展属性</el-button>
          <el-table
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
              label="属性名称">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button type="danger" @click="removeAttributeItems(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/goods/template";
import { listBrand } from "@/api/goods/brand";
import { listSpec } from "@/api/goods/spec";

export default {
  name: "Template",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板管理表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      brandArray:[],
      brandMap:{},
      specArray:[],
      specMap:{},
      brandIds:[],
      specIds:[],
      tableData:[{}]
    };
  },
  created() {
    this.getList();

    listBrand().then(res=>{
      this.brandArray = res.rows
      for(var i in this.brandArray){
        var brand = this.brandArray[i];
        this.brandMap[brand.id] = brand;
      }
    })

    listSpec().then(res=>{
      this.specArray = res.rows
      for(var i in this.specArray){
        var spec = this.specArray[i];
        this.specMap[spec.id] = spec;
      }
    })
  },
  methods: {
    /** 查询模板管理列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        brandIds: null,
        specIds: null,
        attributeItems: null
      };

      this.brandIds = [];
      this.specIds  = [];
      this.tableData = [{}];

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模板管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模板管理";

        // 将数据库中的brandIds 和 specIds转换成 ID 的数组
        var brandIds = JSON.parse(this.form.brandIds);
        for(var i in brandIds){
          this.brandIds.push(brandIds[i].id);
        }
        var specIds = JSON.parse(this.form.specIds);
        for(var i in specIds){
          this.specIds.push(specIds[i].id);
        }
        this.tableData = JSON.parse(this.form.attributeItems)
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 多选下拉框数据格式处理
      var brandArray = new Array();
      for(var i in this.brandIds){
        var id = this.brandIds[i];
        var brand = this.brandMap[id]

        var obj = {"id":id,"name":brand.brandName}
        brandArray.push(obj);
      }
      this.form.brandIds = JSON.stringify(brandArray)

      var specArray = new Array();
      for(var i in this.specIds){
        var id = this.specIds[i];
        var spec = this.specMap[id]

        var obj = {"id":id,"name":spec.name}
        specArray.push(obj);
      }
      this.form.specIds = JSON.stringify(specArray)

      this.form.attributeItems =  JSON.stringify(this.tableData)

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除模板管理编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('goods/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    },
    transformStringArray(string){
      var result = "";
      var array = JSON.parse(string);
      for(var i in array){
        var obj = array[i];
        result +=  ","+obj.name;
      }
      return result.substring(1);
    },
    removeAttributeItems(row){
      var index = this.tableData.indexOf(row);
      this.tableData.splice(index,1)

      if(this.tableData.length == 0){
        this.tableData.push({})
      }

    }
  }
};
</script>
